from json import loads, dumps
import cherrypy
from handlers import handlers_db

class Dispatcher:
    """
    This class is used to perform the CherryPy-specific part of the request handling.
    It calls the handler and passes the JSON decoded body of the request
    """
    def __init__(self, handler):
        self.req_handler = handler  # a callable

    def handle_request(self, *arguments):
        "arguments gets the additional components in the url"
        if cherrypy.request.body:
            body = cherrypy.request.body.read()
        else:
            body = '{}'
        return self.req_handler(body, *arguments)  
    handle_request.exposed = True


class Root(object):
    """
    This is an example www server for handling responses.
    """
    def __init__(self):
        """mount the handlers at the specified urls

        To mount a callable "f" at url "foo" you do:
        self.foo = f
        self.foo.exposed = True

        The loop below does this dynamically
        """
        for url, handler in handlers_db.items():
            print 'Responses for /%s provided by %s' % (url, handler.__class__.__name__)
            setattr(self, url, Dispatcher(handler).handle_request)

if __name__=='__main__':
    cherrypy.quickstart(Root())
